<template>
    <div>
        <div class="ruleMessage" v-if="ruleMessage">
            {{ ruleMessage }}
        </div>
        <div class="e-table">
            <div class="top" v-if="auditState.canModify">
                <div class="left">
                    <div>
                        <el-button size="small" class="btn-greenYellow" @click="add"
                            >新增</el-button
                        >
                        <!-- <el-button @click="save">测试保存</el-button> -->
                    </div>
                </div>
            </div>
            <el-table
                :data="tableData"
                border
                style="width: 100%"
                :cell-class-name="cellClsNm"
                @cell-click="cellClick"
                @cell-mouse-enter="cellMouseEnter"
                @cell-mouse-leave="cellMouseLeave"
                :max-height="$store.state.tableHeight"
                ref="table"
                v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
            >
                <!--  -->
                <el-table-column width="120" label="操作" v-if="auditState.canModify">
                    <template slot-scope="scope">
                        <div>
                            <!-- <i
                                class="el-icon-edit"
                                style="cursor: pointer; font-size: 20px; margin-right: 10px"
                                :class="{
                                    'icon-edit-active-color': MouseEnterId == scope.row.dtlId
                                }"
                                @click="editData(scope.$index)"
                                v-if="!scope.row.write"
                            ></i> -->
                            <i
                                slot="reference"
                                class="el-icon-delete"
                                style="cursor: pointer; font-size: 20px"
                                :class="{
                                    'icon-delete-active-color': MouseEnterId == scope.row.dtlId
                                }"
                                @click="deleteData(scope.$index)"
                            ></i>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="itemNo" label="包件编号" width="150">
                    <!-- slot-scope="{ row }" v-if="row.addData === 1" -->
                    <template slot-scope="{ row }">
                        <div>
                            <el-input
                                v-model="row.itemNo"
                                placeholder="请输入内容"
                                v-if="auditState.canModify"
                                @blur="createRow(row, 'itemNo')"
                            ></el-input>
                            <span v-else>{{ row.itemNo }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="包件名称" width="150">
                    <template slot-scope="{ row }">
                        <div>
                            <el-input
                                v-model="row.name"
                                placeholder="请输入内容"
                                v-if="auditState.canModify"
                                @blur="createRow(row, 'name')"
                            ></el-input>
                            <span v-else>{{ row.name }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="priceLimit"
                    label="租赁最高限价(元)"
                    width="150"
                >
                </el-table-column>
                <el-table-column prop="taxRate" label="清单税率（%）" width="150">
                    <template slot-scope="{ row }">
                        <div>
                            <el-input
                                v-model="row.taxRate"
                                placeholder="请输入税率"
                                v-enterInteger2
                                @blur="inputblur(row, 'taxRate')"
                                v-if="auditState.canModify"
                            ></el-input>
                            <span v-else>{{ row.taxRate }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="freightRate" label="运费税率（%）" width="150">
                    <template slot-scope="{ row }">
                        <div>
                            <el-input
                                v-model="row.freightRate"
                                placeholder="请输入税率"
                                v-enterInteger2
                                @blur="inputblur(row, 'freightRate')"
                                v-if="auditState.canModify"
                            ></el-input>
                            <span v-else>{{ row.freightRate }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="taxAmount" label="清单税额（元）" min-width="150">
                    <template slot-scope="{ row }">
                        <div>
                            <span>{{ row.taxAmount }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="freightTax" label="运费税额（元）" min-width="150">
                    <template slot-scope="{ row }">
                        <div>
                            <span>{{ row.freightTax }}</span>
                            <!-- <el-input
                                v-model.number="tableData[$index].freightTax"
                                placeholder="请输入税额"
                            ></el-input> -->
                        </div>
                    </template>
                </el-table-column>
                <!-- subcontractors只是用来前端显示 -->
                <el-table-column
                    prop="subcontractors"
                    label="供应商名称"
                    width="300"
                    v-if="tenderData.tenderForm !== '1'"
                >
                    <template slot-scope="{ $index }">
                        <el-button @click="testFun('subcontractor', $index)" v-if="Secret"
                            >测试</el-button
                        >
                        <el-input
                            @focus="noFocus"
                            ref="noFocus1"
                            v-model="subcontractor[$index]"
                            v-if="auditState.canModify"
                        >
                            <i
                                class="el-icon-document-copy"
                                slot="suffix"
                                @click="clientSelect('subcontractor', $index)"
                                style="cursor: pointer"
                            >
                            </i>
                        </el-input>
                        <span v-else>{{ subcontractor[$index] }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="planDetails" label="计划编号" width="190">
                    <template slot-scope="{ row, $index }">
                        <div v-if="tableData[$index].planDetails">
                            <div
                                v-for="(item, itemIndex) in plans(row.planDetails)"
                                :key="itemIndex"
                                @click="toPlan(tableData[$index].planDetails, itemIndex)"
                            >
                                <span style="color: blue; cursor: pointer">{{ item }}</span>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <ComPagination
                :total="pagination.total"
                :pageSize.sync="pagination.pageSize"
                :currentPage.sync="pagination.currentPage"
                :tableData.sync="tableData"
                :tableDataIsModel="true"
                @tableDataIsModelFun="tableDataIsModelFun"
                v-if="pagination.total > 10"
            />
            <el-dialog
                title="高级搜索"
                :visible.sync="dialogVisibleSearch"
                width="40%"
                :modal="false"
            >
                <div class="item">
                    <span>机构</span>
                    <el-input v-model="input1" placeholder="请输入内容" size="mini"></el-input>
                </div>
                <div class="item">
                    <span>计划日期</span>
                    <el-date-picker v-model="value1" size="mini"> </el-date-picker>
                    <span class="separate">—</span>
                    <el-date-picker arrow-control v-model="value2" size="mini"> </el-date-picker>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button size="mini" class="btn-greenYellow">重置</el-button>
                    <el-button size="mini" class="btn-blue">确定</el-button>
                </span>
            </el-dialog>
            <!-- <ComMaskAdd ref="ComMaskAdd" @refreshTable="tenderApplyListByEntity" /> -->
        </div>
    </div>
</template>

<script>
import ComPagination from '@/components/pagination/pagination.vue'
// import ComMaskAdd from './mask/add'
// import applyRequest from '@/api/tender/apply.js'
import equipmentLeasingRequest from '@/api/tender/equipmentLeasing.js'
// eslint-disable-next-line no-unused-vars
import { selectDataClient, openAppClient } from '@/utils/common'
import { mapState, mapMutations } from 'vuex'

export default {
    props: {
        comTenderId: { type: String, default: '' },
        addenId: { type: String, default: '' },
        addenDetails: {
            type: Array,
            default: function () {
                return []
            }
        },
        tenderData: {
            type: Object,
            default: function () {
                return {}
            }
        },
        canEdit: {
            type: Boolean,
            default: true
        },
        tableData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 清单数据
        tenderListData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 审核状态
        auditState: {
            type: Object,
            default: function () {
                return {}
            }
        }
    },
    model: {
        prop: 'tableData',
        event: 'change'
    },
    data () {
        return {
            test: '',
            // 主页
            input1: '',
            // mask搜索
            value1: '',
            value2: '',
            dialogVisibleSearch: false,
            MouseEnterId: 0,
            editFormData: {},
            pagination: {
                total: 0,
                pageSize: 20,
                currentPage: 1
            },
            iconActiveColor: {
                id: '',
                type: ''
            },
            Secret: false,
            cloneFormData: {},
            rowDtlId: '',
            cellRowIndex: 0,
            // tenderData: {},
            deleteTableData: [],
            subcontractor: [],
            ruleMessage: '',
            cloneTableData: [],
            initDataState: 0,
            cloneSubcontractor: [],
            cloneSubcontractorsArr: new Array(1000).fill([]) // 用来对比分包商是否修改，是数组，包含所有包间信息的分包商
        }
    },
    computed: {
        ...mapState({
            options: state => state.biddingApplication.dictionaries
        }),
        tenderId () {
            return this.$route.query.tenderId || this.$route.query.billid
        },
        // 计划编号只返回编号
        plans () {
            return function (planNumber) {
                const array = planNumber !== null ? JSON.parse(planNumber) : []
                return array.map(item => item.billNo)
            }
        },
        // 当前清单选择包件id
        dtlId () {
            return this.tenderListData.length !== 0 ? this.tenderListData[0].packageId : ''
        },
        // 已选择的供应商
        selectedIDs () {
            // return index => {
            //     // this.setSelectedInfo(this.tableData)
            //     // openAppClient('/showSelectedData', '选择结果', function () {})
            //     return this.tableData[index].subcontractors[0]?.subcontractorId !== ''
            //         ? this.tableData[index].subcontractors?.map(item => item.subcontractorId)
            //         : []
            // }
            return index => {
                return this.tableData[index].subcontractors
                    .filter(item => item.changeType !== -1)
                    .map(item => item.subcontractorId)
            }
        }
    },
    watch: {
        // tableData: {
        //     handler (val) {
        //         this.$emit('change', val)
        //     },
        //     deep: true
        // }
        // 监听清单
        tenderListData: {
            handler (val) {
                // 第1次启动不监听，直接用后台返的数据
                this.initDataState += 1
                if (this.initDataState > 1) {
                    // 统计整个清单
                    val.forEach((item, index) => {
                        // 清单没数据包件不计算
                        // if (item.length === 0) return
                        // // 计算物资税额
                        // const taxAmount = item.reduce((prev, current) => {
                        //     return (
                        //         prev +
                        //         current.limitPrice *
                        //             current.num *
                        //             current.estimatedServiceTime
                        //     )
                        // }, 0)
                        // // 计算运费税额
                        // const freightTax = item.reduce((prev, current) => {
                        //     return prev + current.freightPrice * current.num
                        // }, 0)
                        this.tableData.forEach((item2, index2) => {
                            if (index === index2) {
                                // 如果包件没数据
                                if (item.length === 0) {
                                    item2.priceLimit = ''
                                    item2.taxAmount = ''
                                    item2.freightTax = ''
                                    item2.planDetails = ''
                                    return
                                }
                                // 计算采购最高价
                                item2.priceLimit = parseFloat(
                                    item
                                        .reduce((prev, cur) => {
                                            return prev + cur.amount
                                        }, 0)
                                        .toFixed(2)
                                )
                                // // 计算物资税额
                                // item2.taxAmount = parseFloat(
                                //     (taxAmount * (item2.taxRate / 100)).toFixed(
                                //         2
                                //     )
                                // )
                                // // 计算运费税额
                                // item2.freightTax = parseFloat(
                                //     freightTax *
                                //         (item2.freightRate / 100).toFixed(2)
                                // )
                                // 计划数据转换计划编号
                                const paln = JSON.stringify(
                                    Array.from(
                                        new Set(
                                            item.map(item => item.planDetails).filter(item => item)
                                        )
                                    ).map(item => JSON.parse(item))
                                )
                                item2.planDetails = paln
                                // if (paln) {
                                //     item2.forEach(item => {
                                //         if (item.dtlId === this.dtlId) {
                                //             // item.changeType = 2
                                //             item.planDetails = paln
                                //             // item.priceLimit = priceLimit
                                //         }
                                //     })
                                // }
                            }
                        })
                    })
                    // console.log('this.tableData', this.tableData)
                }
            },
            deep: true
        },
        // 监听包件
        tableData: {
            handler (val) {
                this.tenderListData.forEach((item, index) => {
                    // 计算物资税额
                    const taxAmount = item.reduce((prev, current) => {
                        return (
                            prev + current.limitPrice * current.num * current.estimatedServiceTime
                        )
                    }, 0)
                    // 计算运费税额
                    const freightTax = item.reduce((prev, current) => {
                        return prev + current.freightPrice * current.num
                    }, 0)
                    val.forEach((item2, index2) => {
                        if (index === index2) {
                            // 计算物资税额
                            item2.taxAmount = parseFloat(
                                (taxAmount * (item2.taxRate / 100)).toFixed(2)
                            )
                            // 计算运费税额
                            item2.freightTax = parseFloat(
                                (freightTax * (item2.freightRate / 100)).toFixed(2)
                            )
                        }
                    })
                })
            },
            deep: true
        }
    },
    components: {
        ComPagination
        // ComMaskAdd
    },
    async created () {
        // this.getAddEchoData() // 获取各种础数据用于新增包件回显
        await this.findByApplyId() // 获取包件列表数据
        // this.tenderApplyFindById() // 获取基础信息
        // console.log('tenderData', this.tenderData)
        // setTimeout(() => {
        //     console.log('tableData', this.tableData)
        // }, 2000)
        this.isTransfer() // 是否是迁移数据
    },
    mounted () {
        const temp = []
        document.onkeydown = e => {
            temp.push(e.keyCode)
            if (temp.length > 4) {
                temp.splice(0, 1)
            }
            if (temp.join('') === '38384040') {
                this.Secret = true
                document.onkeydown = undefined
            }
        }
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        isTransfer () {
            if (this.tenderData.isTransfer === 1) {
                if (this.tableData.length === 0) return
                this.tableData.forEach(item => {
                    item.taxRate = this.tenderData.taxRate
                    item.taxAmount = parseFloat((item.priceLimit * (item.taxRate / 100)).toFixed(4))
                })
            }
        },
        createRow (row) {
            // 没有dtiId就创建包件
            if (row.dtlId === '' && row.addState) {
                delete row.addState
                equipmentLeasingRequest.packageCreate([row]).then(async () => {
                    // row.dtlId = res.dtlId
                    const detailsData = await this.findByApplyId(true) // 只需要结果，不需要操作
                    detailsData.forEach((item, index) => {
                        this.tableData[index].dtlId = item.dtlId
                        this.cloneTableData.push(JSON.parse(JSON.stringify(this.tableData[index])))
                    })
                })
            }
        },
        tableDataIsModelFun (val) {
            this.$emit('change', val)
        },
        inputblur (row, val) {
            // 没有dtiId就创建包件
            if (row.dtlId === '' && row.addState) {
                delete row.addState
                equipmentLeasingRequest.packageCreate([row]).then(async () => {
                    // row.dtlId = res.dtlId
                    const detailsData = await this.findByApplyId(true) // 只需要结果，不需要操作
                    detailsData.forEach((item, index) => {
                        this.tableData[index].dtlId = item.dtlId
                        this.cloneTableData.push(JSON.parse(JSON.stringify(this.tableData[index])))
                    })
                })
            }
            row[val] = isNaN(parseFloat(row[val])) ? 0 : parseFloat(row[val])
            // 转为2位数字
            // if (row[val] !== 0) {
            //     row[val] = String(row[val])
            //     row[val] = parseFloat(row[val][0] + row[val][1])
            // }
        },
        toPlan (item, index) {
            // console.log('item', item)
            const plan = JSON.parse(item)[index]
            const path = 'leasePlanShow'
            // if (plan.type === 1) {
            //     path = 'totalPlanParticulars'
            // } else if (plan.type === 2) {
            //     path = 'sporadicPurchaseParticulars'
            // } else if (plan.type === 3) {
            //     path = 'procuremenPlanShow'
            // } else if (plan.type === 4) {
            //     path = 'momentNeedPlanShow'
            // } else if (plan.type === 5) {
            //     path = 'monthPlanParticulars'
            // } else if (plan.type === 6) {
            //     path = 'revolveLeasePlanShow'
            // }
            // this.setSelectedInfo(`/${path}?isview=true&billid=${plan.billid}`)
            // openAppClient('/showSelectedData', '选择结果', function () {})
            openAppClient(`/${path}?isview=true&billid=${plan.billid}`, '查看计划')
            // 总计划  totalPlan   零星采购计划 sporadicPurchase   月计划 monthPlan   集采汇总 purchaseCollect
            //             procuremenPlanList 采购计划
            // momentNeedPlanList 临时需用
            // revolveLeasePlanList 租赁
        },
        testFun (name, index) {
            const val = [
                {
                    businessScopeId: null,
                    businessScopeName: null,
                    businessTypeKey: '',
                    businessTypeValue: '-1',
                    creditCode: '91440606MA53UM491A',
                    id: '02f0f06d-ee76-4724-9a37-ca9418b8d303',
                    orgId: 'aca91a6dc32c-b02d-7a4d-30a3-df00f82e',
                    orgName: '四川公路桥梁建设集团有限公司伦桂路北段工程施工项目经理部',
                    outerId: '02f0f06d-ee76-4724-9a37-ca9418b8d303',
                    outerName: '佛山市顺德区北控科锐再生资源有限公司',
                    outerType: '物资供应商',
                    outerTypeValue: '11',
                    type: 1
                }
            ]
            // 判断分包商是否发生变化
            const row = this.tableData[index]
            // 是否新增
            // 遍历客户端选择数据
            val.forEach(item => {
                const addItem = this.cloneSubcontractorsArr[index].find(
                    item2 => item2.subcontractorId === item.id
                )
                // 在原clone数据里没找到，说明是新增
                if (addItem === undefined) {
                    row.subcontractors.push({
                        changeType: 1,
                        subcontractorId: item.id,
                        subcontractorName: item.outerName,
                        type: parseInt(item.type),
                        billId: this.billId,
                        packageId: row.dtlId
                    })
                    return
                }
            })
            // 是否删除
            // 遍历克隆的初始数据
            this.cloneSubcontractorsArr[index].forEach(item => {
                const delItem = val.find(item2 => item2.id === item.subcontractorId)
                // 在原clone数据里没找到，说明删除了
                if (delItem === undefined) {
                    row.subcontractors.find(
                        item3 => item3.subcontractorId === item.subcontractorId
                    ).changeType = -1
                    // 找到了则不变
                } else {
                    row.subcontractors.find(
                        item3 => item3.subcontractorId === item.subcontractorId
                    ).changeType = 0
                }
            })
            console.log('row', row)
            console.log('this.cloneSubcontractorsArr', this.cloneSubcontractorsArr)
            // this.setSelectedInfo(row)
            // openAppClient('/showSelectedData', 'row', function () {})
            // 前端显示的
            this.$set(
                this.subcontractor,
                index,
                row.subcontractors
                    .filter(value => value.changeType !== -1)
                    .map(value => value.subcontractorName)
                    .join(',')
            )
            console.log('this.subcontractor', this.subcontractor)
        },
        clientSelect (name, index) {
            console.log('this.selectedIDs(index)', this.selectedIDs(index))
            if (name === 'subcontractor') {
                // console.log('selectedIDs', this.selectedIDs())
                selectDataClient({
                    SelectServiceToken: '/outer/outer/tnder/get/outer', // 客户端对应方法名
                    IsSingleMode: false, // 是否单选 true 单选 false 多选
                    SelectedIDs: this.selectedIDs(index),
                    InitParamsStr: JSON.stringify({
                        tnderType: null,
                        material: true
                    }),
                    Title: '选择供应商' // 标题
                }).then(val => {
                    // this.setSelectedInfo(val)
                    // openAppClient('/showSelectedData', 'val', function () {})
                    // 判断分包商是否发生变化
                    const row = this.tableData[index]
                    // 是否新增
                    // 遍历客户端选择数据
                    val.forEach(item => {
                        const addItem = this.cloneSubcontractorsArr[index].find(
                            item2 => item2.subcontractorId === item.id
                        )
                        // 在原clone数据里没找到，说明是新增
                        if (addItem === undefined) {
                            row.subcontractors.push({
                                changeType: 1,
                                subcontractorId: item.id,
                                subcontractorName: item.outerName,
                                type: parseInt(item.type),
                                billId: this.billId,
                                packageId: row.dtlId,
                                creditCode: item.creditCode
                            })
                        }
                    })
                    // 是否删除
                    // 遍历克隆的初始数据
                    // 克隆没有数据说明是导入的，直接等于选择的即可
                    if (this.cloneSubcontractorsArr[index].length === 0) {
                        row.subcontractors = []
                        val.forEach(item => {
                            const addItem = this.cloneSubcontractorsArr[index].find(
                                item2 => item2.subcontractorId === item.id
                            )
                            // 在原clone数据里没找到，说明是新增
                            if (addItem === undefined) {
                                row.subcontractors.push({
                                    changeType: 1,
                                    subcontractorId: item.id,
                                    subcontractorName: item.outerName,
                                    type: parseInt(item.type),
                                    billId: this.billId,
                                    packageId: row.dtlId,
                                    creditCode: item.creditCode
                                })
                            }
                        })
                        // 有克隆数据，要和原单做对比
                    } else {
                        this.cloneSubcontractorsArr[index].forEach(item => {
                            const delItem = val.find(item2 => item2.id === item.subcontractorId)
                            // 在原clone数据里没找到，说明删除了
                            if (delItem === undefined) {
                                row.subcontractors.find(
                                    item3 => item3.subcontractorId === item.subcontractorId
                                ).changeType = -1
                                // 找到了则不变
                            } else {
                                row.subcontractors.find(
                                    item3 => item3.subcontractorId === item.subcontractorId
                                ).changeType = 0
                            }
                        })
                    }
                    // this.setSelectedInfo(row)
                    // openAppClient('/showSelectedData', 'row', function () {})
                    // 前端显示的
                    this.$set(
                        this.subcontractor,
                        index,
                        row.subcontractors
                            .filter(value => value.changeType !== -1)
                            .map(value => value.subcontractorName)
                            .join(',')
                    )
                    // 没有dtiId就创建包件
                    if (row.dtlId === '' && row.addState) {
                        delete row.addState
                        equipmentLeasingRequest.packageCreate([row]).then(async () => {
                            // row.dtlId = res.dtlId
                            const detailsData = await this.findByApplyId(true) // 只需要结果，不需要操作
                            detailsData.forEach((item, index) => {
                                this.tableData[index].dtlId = item.dtlId
                                this.cloneTableData.push(
                                    JSON.parse(JSON.stringify(this.tableData[index]))
                                )
                            })
                        })
                    }
                })
            }
        },
        noFocus () {
            this.$refs.noFocus1?.blur()
        },
        deleteData (index) {
            const callBack = () => {
                // if (this.tableData[index].changeType !== 1) {
                this.tableData[index].changeType = -1
                this.deleteTableData.push(this.tableData[index])
                // }
                this.tableData.splice(index, 1)
                this.subcontractor.splice(index, 1) //删除前端显示的分包商
            }
            this.clientPop(
                'info',
                '是否删除包件？删除包件的同时会删除包件对应的招标清单，请谨慎操作！',
                callBack
            )
        },
        // tenderApplyFindById () {
        //     applyRequest.tenderApplyFindById(this.tenderId).then(res => {
        //         // 表单提交信息映射基础招标信息
        //         this.tenderData = res
        //         console.log(this.tenderData, 'tenderData')
        //     })
        // },
        async getAddEchoData () {
            // 表单提交信息映射基础招标信息
            const tenderData = this.tenderData
            Object.keys(this.formData).forEach(formDataKey => {
                Object.keys(tenderData).forEach(tenderDataKey => {
                    if (formDataKey === tenderDataKey) {
                        this.formData[formDataKey] = tenderData[tenderDataKey]
                    }
                })
            })
            // 部分数据对应不上，需要增改
            // 备份一份formdata增改formdata时重置
            this.cloneFormData = JSON.parse(JSON.stringify(this.formData))
        },
        detailRule () {
            // 拟招标内容明细验证
            const ruleMessageArr = []
            const ComDetailsOfProposedIndex = this
            if (ComDetailsOfProposedIndex.tableData.length === 0) {
                // ComDetailsOfProposedIndex.ruleMessage = '未添加包件'
                // this.onChangeTab({ name: 'detail' })
                return true
            }
            ComDetailsOfProposedIndex.tableData.forEach((item, index) => {
                index += 1
                if (item.itemNo === '') {
                    ruleMessageArr.push(`包件${index}包件编号不能为空`)
                }
                if (item.name == '') {
                    ruleMessageArr.push(`包件${index}包件名称不能为空`)
                }
                // 除了公开招标，其他招标方式分包商不能为空
                if (this.tenderData.tenderForm !== '1' && item.subcontractors.length < 3) {
                    if (item.subcontractors.length === 0) {
                        ruleMessageArr.push(`包件${index}分包商不能为空`)
                    } else {
                        // 邀请招标、询价
                        if (
                            (this.tenderData.tenderForm === '0' ||
                                this.tenderData.tenderForm === '2') &&
                            item.subcontractors.length < 3
                        ) {
                            ruleMessageArr.push(`包件${index}至少选择三家分包商`)
                            // 竞争性谈判
                        } else if (
                            this.tenderData.tenderForm === '3' &&
                            item.subcontractors.length < 2
                        ) {
                            ruleMessageArr.push(`包件${index}至少选择两家分包商`)
                        } else if (
                            this.tenderData.tenderForm === '4' &&
                            item.subcontractors.length < 1
                        ) {
                            ruleMessageArr.push(`包件${index}至少选择一家分包商`)
                        }
                    }
                }
                console.log('typeof item.taxRate', typeof item.taxRate)
                console.log('item.taxRate', item.taxRate)
                if (typeof item.taxRate !== 'number') {
                    ruleMessageArr.push(`包件${index}清单税率必须为数字`)
                } else if (item.taxRate < 0 || item.taxRate > 100) {
                    ruleMessageArr.push(`包件${index}清单税率必须在0-100之间`)
                }
                if (typeof item.freightRate !== 'number') {
                    ruleMessageArr.push(`包件${index}运费税率必须为数字`)
                } else if (item.freightRate < 0 || item.taxRate > 100) {
                    ruleMessageArr.push(`包件${index}运费税率必须在0-100之间`)
                }
                if (ruleMessageArr.length !== 0) {
                    ComDetailsOfProposedIndex.ruleMessage = ruleMessageArr.join('，')
                    this.$emit('onChangeTab', { name: 'detail' })
                    // this.onChangeTab({ name: 'detail' })
                }
            })
            this.ruleMessage = ruleMessageArr.join(',')
            if (ruleMessageArr.length === 0) {
                return true
            } else {
                return false
            }
        },
        ifEdit (tableData) {
            console.log('tableData', this.tableData)
            console.log('cloneTableData', this.cloneTableData)
            let state = false
            // 判断每条数据是否修改
            tableData.forEach(item => {
                this.cloneTableData.forEach(item2 => {
                    if (
                        item.dtlId === item2.dtlId &&
                        JSON.stringify(item) !== JSON.stringify(item2)
                    ) {
                        // 分包商在导入后就判断是否新增、删除了，没修改状态
                        // const cloneTableDataSubcontractorsArr =
                        //     item2.subcontractors.map(
                        //         item => item.subcontractorId
                        //     )
                        // // 判断分包商是否修改
                        // item.subcontractors.forEach(item3 => {
                        //     if (
                        //         cloneTableDataSubcontractorsArr.includes(
                        //             item3.subcontractorId
                        //         )
                        //     ) {
                        //         item3.changeType = 0
                        //     } else {
                        //         item3.changeType = 1
                        //     }
                        // })
                        state = true
                        item.changeType = 2
                    }
                })
            })
            // 边界情况：有数据删除
            if (this.deleteData.length !== 0) {
                state = true
            }
            return state
        },
        //         ifEditSubcontractor () {
        //             this.subcontractor.forEach((item)=>{
        // this.cloneSubcontractor.forEach
        //             })
        //         },
        // 包件保存
        async save () {
            // this.setSelectedInfo(this.tableData)
            // openAppClient('/showSelectedData', '选择结果', function () {})
            if (!this.ifEdit(this.tableData)) {
                return Promise.resolve()
            }
            // 包件验证
            // if (this.detailRule()) {
            const tableData = [...this.tableData, ...this.deleteTableData]
            // this.setSelectedInfo(tableData)
            // openAppClient('/showSelectedData', '选择结果', function () {})                // 招标修改包件
            await equipmentLeasingRequest.packageCreate(tableData).then(() => {
                this.ruleMessage = ''
                this.findByApplyId()
            })
            // 未通过包件验证
            // } else {
            //     // this.ruleMessage = ''
            //     return Promise.reject()
            // }
            // if (tableData.length === 0) return
            // // 表单提交信息映射基础招标信息
            // if (this.comTenderId) {
            //     // 补遗修改包件
            //     if (this.addenDetails.length === 0) {
            //         // 创建补遗包件
            //         tableData.forEach(value => {
            //             value.changeBillId = this.addenId
            //             value.changeType = 1
            //             value.subcontractor.forEach(value2 => {
            //                 value2.recordId = ''
            //             })
            //         })
            //     } else {
            //         // 修改补遗包件
            //         tableData.forEach(value => {
            //             value.changeBillId = this.addenId
            //         })
            //     }
            //     await applyRequest.packageCreate(tableData)
            // } else {
            //     // this.setSelectedInfo(tableData)
            //     // openAppClient('/showSelectedData', '选择结果', function () {})
            //     // 招标修改包件
            //     await engineeringOtherRequest.packageCreate(tableData)
            // }
        },
        add () {
            this.tableData.push({
                billId: this.tenderId,
                changeType: 1,
                dtlId: '',
                freightRate: 0,
                freightTax: 0,
                itemNo: '',
                name: '',
                priceLimit: 0,
                subcontractors: [
                    // 假数据
                    // {
                    //     subcontractorId: '1513441890867539970',
                    //     subcontractorName: '大成都建筑',
                    //     type: 0,
                    //     changeType: 1
                    // },
                    // {
                    //     subcontractorId: '1513692270402662402',
                    //     subcontractorName: '成都建筑公司',
                    //     type: 0,
                    //     changeType: 1
                    // },
                    // {
                    //     subcontractorId: '1513762252729806850',
                    //     subcontractorName: '劳务单位',
                    //     type: 0,
                    //     changeType: 1
                    // }
                ],
                taxAmount: 0,
                taxRate: 0,
                addState: true
                // write: 1
            })
            // }
        },
        // eslint-disable-next-line no-unused-vars
        cellClick (row, column, cell, event) {
            console.log('row', row)
            console.log('this.tableData', this.tableData)
            // console.log('rowIndex', rowIndex)
            // if (column.label === '关闭日期') {
            //     this.$router.push({
            //         path: './bidClosingShow',
            //         query: { billid: row.billId }
            //     })
            // }
        },
        // iconMouseover (id, type) {
        //     this.iconActiveColor.id = id
        //     this.iconActiveColor.type = type
        // },
        // iconMouseleave () {
        //     this.iconActiveColor.id = {
        //         id: '',
        //         type: ''
        //     }
        // },
        // 点击编辑图标
        editData (index) {
            // this.tableData[index].write = true
            this.tableData[index].changeType = 2
            // // 取消其他数据的编辑状态
            // this.tableData.forEach((value, key) => {
            //     if (value.editData) {
            //         delete this.tableData[key].editData
            //     }
            // })
            // // 本条数据编辑状态
            // this.tableData[index].editData = 1
            // // 编辑数据
            // this.editFormData = JSON.parse(JSON.stringify(this.cloneFormData))
            // // 表单提交信息映射基础招标信息
            // const tenderData = this.tableData[index]
            // Object.keys(this.editFormData).forEach(formDataKey => {
            //     Object.keys(tenderData).forEach(tenderDataKey => {
            //         if (formDataKey === tenderDataKey) {
            //             this.editFormData[formDataKey] = tenderData[tenderDataKey]
            //         }
            //     })
            // })
        },
        // async ifGetDetailsData () {
        //     return new Promise((resolve, reject) => {
        //         const temp = setInterval(() => {
        //             if (this.cloneTableData.length !== 0) {
        //                 clearInterval(temp)
        //                 resolve()
        //             } else {
        //                 reject()
        //             }
        //         }, 100)
        //         setTimeout(() => {
        //             clearInterval(temp)
        //             resolve()
        //         }, 2000)
        //     })
        // },
        async findByApplyId (onlyRes = false) {
            // 招标包件
            const res = await await equipmentLeasingRequest.packageListByEntity({
                limit: 20,
                page: 1,
                tenderApplyId: this.comTenderId || this.tenderId
            })
            if (res.length === 0) return
            if (onlyRes) {
                return Promise.resolve(res)
            }
            await this.$emit('change', res)
            // 前端显示的分包商
            res.forEach((value, index) => {
                if (value.subcontractors.length === 0) return
                this.$set(
                    this.subcontractor,
                    index,
                    value.subcontractors.map(value => value.subcontractorName).join(',')
                )
                this.cloneSubcontractorsArr[index] = JSON.parse(
                    JSON.stringify(value.subcontractors)
                )
            })
            console.log('subcontractor', this.subcontractor)
            this.tableData.forEach(value => {
                value.billId = this.tenderId
                value.changeType = 0
                value.subcontractors.forEach(item => {
                    item.changeType = 0
                })
            })
            this.cloneTableData = JSON.parse(JSON.stringify(this.tableData))
            this.cloneSubcontractor = JSON.parse(JSON.stringify(this.subcontractor))
            this.pagination.total = res.totalCount || res.length
        },
        // eslint-disable-next-line no-unused-vars
        formatter (row, column, cellValue, index) {
            if (column.label === '采购方式') {
                return this.options.tenderForm.map(item => {
                    if (String(index) === cellValue) {
                        return item
                    }
                })
            } else if (column.label === '招标类型') {
                return this.options.tenderClass.map((item, index) => {
                    if (index + 1 === cellValue) {
                        return item
                    }
                })
            } else if (column.label === '状态') {
                const state = new Map(Object.entries(this.options.state))
                const arr = []
                state.forEach((item, index) => {
                    arr[index] = item
                })
                return arr.map((item, index) => {
                    if (index === cellValue) {
                        return item
                    }
                })
            } else if (column.label === '发布状态') {
                return this.options.releaseState.map((item, index) => {
                    if (index === cellValue) {
                        return item
                    }
                })
            }
        },
        openAddDialog () {
            this.$router.push('./bidClosingAdd')
            // this.$refs.ComMaskAdd.getVuexData()
            // this.$refs.ComMaskAdd.dialogVisible = true
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.dtlId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        }
    }
}
</script>

<style lang="scss" scoped>
.ruleMessage {
    margin-bottom: 20px;
    color: red;
}
.e-table {
    background: #fff;
}
</style>
